package cn.serenedream.sbblog.backend;

import cn.serenedream.sbblog.Blog;
import cn.serenedream.sbblog.BlogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller("BackendBlogController")
@RequestMapping("backend/blog")
public class BlogController {

    @Autowired
    BlogRepository blogRepository;

    @GetMapping("{listId}")
    public String list(@PathVariable(required = false) int listId, Model model) {
        List<Blog> blog = blogRepository.findAll();
        // 当输入值不正确时跳转为正确值
        if (listId <= 0) {
            listId = 1;
        }
        if (listId > blog.size()) {
            listId = blog.size();
        }

        // 用来保存当前的 id 的值
        int id = listId;
        model.addAttribute("id", id);

        // 设置页面显示的数量
        int number = 10;

        int num;
        if (blog.size() % number != 0) {
            num = (blog.size() / number) + 1;
        } else {
            num = (blog.size() / number);
        }

        // 显示列表元素
        model.addAttribute("total", "共 " + blog.size() + " 条记录，当前第 " + id + "/" + num + " 页");

        // 向前端传递上下页信息
        model.addAttribute("X", (id + 1) > num ? num : (id + 1));
        model.addAttribute("S", (id - 1) < 0 ? 0 : (id - 1));

        int begin = (id - 1) * number;
        int end = (id * number) > blog.size() ? blog.size() : (id * number);
        blog = blog.subList(begin, end);
        model.addAttribute("blogs", blog);

        return "backend/list";
    }

    @GetMapping("show/{id}")
    public String show(@PathVariable Long id) {
        return "backend/show";
    }

    @GetMapping("add")
    public String add() {
        return "backend/add";
    }

    //    @ResponseBody
    @PostMapping(value = "add")
    public String save(Blog blog) {
        System.out.println(blog);
        System.out.println("接收到 POST 请求");
        blogRepository.save(blog);
        return "redirect:/backend/blog";
    }

    @GetMapping("edit")
    public String edit() {
        return "backend/edit";
    }

    @ResponseBody
    @PostMapping("edit")
    public String update() {
        System.out.println("这是处理 form 表单的语句， 接收到 post 请求");
        return "修改成功";
    }

    @GetMapping("delete/{id}")
    public String delete(@PathVariable Long id) {
        blogRepository.deleteById(id);
        return "redirect:/backend/blog";
    }
}
